from model.company import CompanyDao
from model.address import AddressDao
from model.city import CityDao

from lib.validator import Validator
from lib.form import Form

from bson.dbref import DBRef
from flask import request
from flask_login import login_user, current_user
import time

from service import Service

class CompanyService(Service):
    def __init__(self):
        self.dao = CompanyDao()
        self.address_dao = AddressDao()
        self.city_dao = CityDao()
        
    def get_companies(self, query={}):
        """ Get company datas for display
        """
        companies = []
        _companies = self.dao.find(query)
        for _company in _companies:
            address = self.address_dao.find_one({'_id':_company.address['_id']})
            city = self.city_dao.find_one({'_id':address.city['_id']})
            companies.append({"name":_company.name, 
                          "description":_company.description, 
                          "street":address.street,
                          "city": "{0} {1} {2}".format(city.name, city.province, city.country),
                          "postcode":address.postcode})
        return companies


    def submit_company(self, inputs):
        # Submit address
        
        # Submit company
        if inputs['mode'] == 'edit':
            #company = company_dao.update_company(inputs['id, inputs['name, inputs['description)
            return None
        elif inputs['mode'] == 'new':
            city = self.city_dao.find_one({'name':inputs['city'], 'province':inputs['province'], 'country':inputs['country']})
            city_dbref = DBRef('cities', city._id )
            address_dict = {'street':inputs['street'], 'postcode':inputs['postcode'], 'city_ref':city_dbref}
            address = self.address_dao.find_one(address_dict)

            admin_dbref = DBRef('users', inputs['admin_id'] )
            
            _dict = {'name':inputs['name'],
                     'description': inputs['description'],
                     'admin_ref': admin_dbref}
            
            if address is None:
                address_id = self.address_dao.save(address_dict)
                _dict['address_ref'] = DBRef('addresses', address_id)
            else:
                _dict['address_ref'] = DBRef('addresses', address._id)
                
            return self.dao.save(_dict)


class CompanyValidator(Validator):
    def __init__(self):
        Validator.__init__(self)
              
        self.rules = {'name': { 
                                'required' : [None, True],
                                'minlength':[None, 1],
                                'maxlength':[None, 256]
                                },
                      'description': { 
                                'maxlength':[None, 256]
                                }
        }

    
class CompanyForm(Form):
    """ Submit user form
    """
    def __init__(self):
        """Only accept POST request
        """
        Form.__init__(self)
        self.validator = CompanyValidator()
        
        if self.is_submitted():
            self.raw_inputs = self.get_raw_inputs()
            self.inputs = self.get_inputs(self.raw_inputs)
            self.errors = self.validator.validate(self.inputs)

    def get_inputs(self, raw_inputs):                
        """ Convert inputs type
        """
        return {'name': raw_inputs['name'],
               'description': raw_inputs['description'],
               'unit': raw_inputs['unit'],
               'street': raw_inputs['street'],
               'postcode': raw_inputs['postcode'],
               'city': raw_inputs['city'],
               'province': raw_inputs['province'],
               'country':'CA',
               'admin_id':current_user._id    
        }
        
    def has_error(self):
        return self.errors != []